import cv2
import numpy as np
import os


def determine(image):
    gray = image
    threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    border_thickness = 2
    height, width = threshold.shape

    threshold[0:border_thickness + 45, :] = 0
    threshold[height - (border_thickness + 45):height, :] = 0
    threshold[:, 0:border_thickness + 45] = 0
    threshold[:, width - (border_thickness + 45):width] = 0
    threshold[0:669, 0:205] = 0
    threshold[530:669, 0:350] = 0
    threshold[0:520, 680:1084] = 0

    element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 9))
    element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (24, 6))
    dilation = cv2.dilate(threshold, element2, iterations=1)
    erosion = cv2.erode(dilation, element1, iterations=1)
    dilation2 = cv2.dilate(erosion, element2, iterations=3)

    contours, hierarchy = cv2.findContours(dilation2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    resize_copy = gray.copy()
    res = cv2.drawContours(resize_copy, contours, -1, (255, 0, 0), 2)

    positions = []
    resize_copy = gray.copy()
    index = 0
    for contour in reversed(contours):
        epsilon = 0.002 * cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, epsilon, True)
        x, y, w, h = cv2.boundingRect(approx)
        if h > 10 and x < 600 and y < 750 and x > 20 and y > 20:
            res = cv2.rectangle(resize_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)
            positions.append((x, y, w, h))

    positions.sort(key=lambda p: p[1])
    index = 0
    while index < len(positions) - 1:
        if positions[index + 1][1] - positions[index][1] < 10:
            temp_list = [positions[index + 1], positions[index]]
            for i in range(index + 1, len(positions)):
                if positions[i + 1][1] - positions[i][1] < 10:
                    temp_list.append(positions[i + 1])
                else:
                    break
            temp_list.sort(key=lambda p: p[0])
            positions[index:(index + len(temp_list))] = temp_list
            index = index + len(temp_list) - 1
        else:
            index += 1

    print(positions)

    flag = 0
    for position in positions:
        x = position[0]
        y = position[1]
        w = position[2]
        h = position[3]
        sub_image = resize_copy[y:y + h, x + 5:x + w - 5]
        flag += 1
        output_filename = f'output/sub_image_{flag}.png'

        cv2.imwrite(output_filename, sub_image)


def determinenew(image, timepath, uuids):
    gray = image
    threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    border_thickness = 2
    height, width = threshold.shape

    threshold[0:border_thickness + 45, :] = 0
    threshold[height - (border_thickness + 45):height, :] = 0
    threshold[:, 0:border_thickness + 45] = 0
    threshold[:, width - (border_thickness + 45):width] = 0
    threshold[0:669, 0:205] = 0
    threshold[530:669, 0:350] = 0
    threshold[0:520, 680:1084] = 0

    element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 9))
    element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (24, 6))
    dilation = cv2.dilate(threshold, element2, iterations=1)
    erosion = cv2.erode(dilation, element1, iterations=1)
    dilation2 = cv2.dilate(erosion, element2, iterations=3)

    contours, hierarchy = cv2.findContours(dilation2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    resize_copy = gray.copy()
    res = cv2.drawContours(resize_copy, contours, -1, (255, 0, 0), 2)

    positions = []
    resize_copy = gray.copy()
    index = 0
    for contour in reversed(contours):
        epsilon = 0.002 * cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, epsilon, True)
        x, y, w, h = cv2.boundingRect(approx)
        if h > 10 and x < 600 and y < 750 and x > 20 and y > 20:
            res = cv2.rectangle(resize_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)
            positions.append((x, y, w, h))

    positions.sort(key=lambda p: p[1])
    index = 0
    while index < len(positions) - 1:
        if positions[index + 1][1] - positions[index][1] < 10:
            temp_list = [positions[index + 1], positions[index]]
            for i in range(index + 1, len(positions)):
                if positions[i + 1][1] - positions[i][1] < 10:
                    temp_list.append(positions[i + 1])
                else:
                    break
            temp_list.sort(key=lambda p: p[0])
            positions[index:(index + len(temp_list))] = temp_list
            index = index + len(temp_list) - 1
        else:
            index += 1

    print(positions)
    # 创建日期文件夹（如果不存在）
    date_folder = f'output/{timepath}/{uuids}'

    if not os.path.exists(date_folder):
        os.makedirs(date_folder)

    flag = 0
    for position in positions:
        x = position[0]
        y = position[1]
        w = position[2]
        h = position[3]
        sub_image = resize_copy[y:y + h, x + 5:x + w - 5]
        flag += 1
        output_filename = f'output/{timepath}/{uuids}/sub_image_{flag}.png'

        cv2.imwrite(output_filename, sub_image)


def determinenew_back(image, timepath, uuids):
    try:
        date_folder = f'output/{timepath}/{uuids}'
        if not os.path.exists(date_folder):
            os.makedirs(date_folder)

        # 裁剪关键区域
        issue_org_text = image[440:530, 200:920]
        valid_date_text = image[528:622, 236:980]

        # 添加自适应锐化
        def auto_sharpen(img):
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) == 3 else img
            # 根据图像对比度自动调整锐化强度
            contrast = cv2.convertScaleAbs(gray).std()
            kernel = np.array([[0, -1, 0], [-1, 5 + contrast / 50, -1], [0, -1, 0]])
            return cv2.filter2D(img, -1, kernel)

        issue_org_text = auto_sharpen(issue_org_text)

        valid_date_text = auto_sharpen(valid_date_text)

        issue_org_text = cv2.resize(issue_org_text,
                                    (issue_org_text.shape[1] // 2, issue_org_text.shape[0] // 2),
                                    interpolation=cv2.INTER_AREA)
        valid_date_text = cv2.resize(valid_date_text,
                                     (valid_date_text.shape[1] // 2, valid_date_text.shape[0] // 2),
                                     interpolation=cv2.INTER_AREA)

        # 保存结果
        cv2.imwrite(f'{date_folder}/sub_image_back_1.png', issue_org_text)
        cv2.imwrite(f'{date_folder}/sub_image_back_2.png', valid_date_text)


    except Exception as e:
        print(f"Error in determinenew_back: {str(e)}")


def determinenew_back_old(image, timepath, uuids):
    gray = image
    threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    border_thickness = 2
    height, width = threshold.shape

    # 调整边界去除逻辑以适应背面布局
    threshold[0:border_thickness + 20, :] = 0
    threshold[height - (border_thickness + 20):height, :] = 0
    threshold[:, 0:border_thickness + 20] = 0
    threshold[:, width - (border_thickness + 20):width] = 0
    # 去除特定区域的干扰，根据实际情况调整
    threshold[0:500, 0:200] = 0
    threshold[500:600, 0:300] = 0
    threshold[0:500, 700:1000] = 0

    element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 9))
    element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (24, 6))
    dilation = cv2.dilate(threshold, element2, iterations=1)
    erosion = cv2.erode(dilation, element1, iterations=1)
    dilation2 = cv2.dilate(erosion, element2, iterations=3)

    contours, hierarchy = cv2.findContours(dilation2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    resize_copy = gray.copy()
    res = cv2.drawContours(resize_copy, contours, -1, (255, 0, 0), 2)

    positions = []
    resize_copy = gray.copy()
    index = 0
    for contour in reversed(contours):
        epsilon = 0.002 * cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, epsilon, True)
        x, y, w, h = cv2.boundingRect(approx)
        if h > 10 and x < 600 and y < 750 and x > 20 and y > 20:
            res = cv2.rectangle(resize_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)
            positions.append((x, y, w, h))

    positions.sort(key=lambda p: p[1])
    index = 0
    while index < len(positions) - 1:
        if positions[index + 1][1] - positions[index][1] < 10:
            temp_list = [positions[index + 1], positions[index]]
            for i in range(index + 1, len(positions)):
                if positions[i + 1][1] - positions[i][1] < 10:
                    temp_list.append(positions[i + 1])
                else:
                    break
            temp_list.sort(key=lambda p: p[0])
            positions[index:(index + len(temp_list))] = temp_list
            index = index + len(temp_list) - 1
        else:
            index += 1

    print(positions)
    # 创建日期文件夹（如果不存在）
    date_folder = f'output/{timepath}/{uuids}'

    if not os.path.exists(date_folder):
        os.makedirs(date_folder)

    flag = 0
    for position in positions:
        x = position[0]
        y = position[1]
        w = position[2]
        h = position[3]
        sub_image = resize_copy[y:y + h, x + 5:x + w - 5]
        flag += 1
        output_filename = f'output/{timepath}/{uuids}/sub_image_back_{flag}.png'
        cv2.imwrite(output_filename, sub_image)


# def determinenew_back(image, timepath, uuids):
#     try:
#         print(111)
#         date_folder = f'output/{timepath}/{uuids}'
#         if not os.path.exists(date_folder):
#             os.makedirs(date_folder)

#             # 裁剪关键区域
#         issue_org_text = image[440:530, 200:920]
#         valid_date_text = image[528:622, 236:980]
#         # 将裁剪后的区域背景锐化为纯白色
#         def sharpen_background_to_white(img):
#             print(111)
#             gray = img
#             _, binary = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
#             white_background = np.ones_like(img) * 255
#             white_background[binary == 0] = img[binary == 0]
#             print("white_background shape:", white_background)
#             return white_background
#         issue_org_text = sharpen_background_to_white(issue_org_text)
#         valid_date_text = sharpen_background_to_white(valid_date_text)
#         # 调整大小
#         issue_org_text = cv2.resize(issue_org_text, (issue_org_text.shape[1]//2,
#                                                      issue_org_text.shape[0]//2), interpolation=cv2.INTER_AREA)
#         valid_date_text = cv2.resize(valid_date_text, (valid_date_text.shape[1]//2,
#                                                       valid_date_text.shape[0]//2), interpolation=cv2.INTER_AREA)
#         # 保存结果
#         cv2.imwrite(f'{date_folder}/sub_image_back_1.png', issue_org_text)
#         cv2.imwrite(f'{date_folder}/sub_image_back_2.png', valid_date_text)
#         # cv2.imwrite('sub_image_back_1.png', issue_org_text)
#         # cv2.imwrite('sub_image_back_2.png', valid_date_text)

#     except Exception as e:
#         print(f"Error in determinenew_back: {str(e)}")